<template>
  <div class="student-statistics">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>学生统计概览</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">学生总数</div>
                <div class="stat-value">{{ summaryData.totalStudents }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">男生人数</div>
                <div class="stat-value">{{ summaryData.maleCount }}</div>
                <div class="stat-trend">
                  <span>{{ summaryData.malePercentage }}%</span>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">女生人数</div>
                <div class="stat-value">{{ summaryData.femaleCount }}</div>
                <div class="stat-trend">
                  <span>{{ summaryData.femalePercentage }}%</span>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">违纪学生</div>
                <div class="stat-value">{{ summaryData.violationCount }}</div>
                <div class="stat-trend">
                  <span>{{ summaryData.violationPercentage }}%</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>班级学生分布</span>
            </div>
          </template>
          <div ref="classPieChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>学历分布</span>
            </div>
          </template>
          <div ref="degreeBarChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>性别分布</span>
            </div>
          </template>
          <div ref="genderPieChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>违纪情况</span>
            </div>
          </template>
          <div ref="violationBarChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>毕业年份分布</span>
              <div>
                <el-radio-group v-model="gradRange" size="small" @change="handleGradRangeChange">
                  <el-radio-button label="year">按年</el-radio-button>
                  <el-radio-button label="month">按月</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div ref="gradLineChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const students = ref([])
const summaryData = ref({
  totalStudents: 0,
  maleCount: 0,
  femaleCount: 0,
  malePercentage: 0,
  femalePercentage: 0,
  violationCount: 0,
  violationPercentage: 0
})

const gradRange = ref('year')

const classPieChart = ref(null)
const degreeBarChart = ref(null)
const genderPieChart = ref(null)
const violationBarChart = ref(null)
const gradLineChart = ref(null)

// 从API获取学生数据
const fetchStudents = async () => {
  try {
    const response = await axios.get('http://localhost:8080/student')
    students.value = response.data.data
    calculateSummaryData()
    renderCharts()
  } catch (error) {
    console.error('获取学生数据失败:', error)
  }
}

// 计算汇总数据
const calculateSummaryData = () => {
  const total = students.value.length
  const males = students.value.filter(s => s.gender === 1).length
  const females = students.value.filter(s => s.gender === 2).length
  const violations = students.value.filter(s => s.violationCount > 0).length
  
  summaryData.value = {
    totalStudents: total,
    maleCount: males,
    femaleCount: females,
    malePercentage: ((males / total) * 100).toFixed(1),
    femalePercentage: ((females / total) * 100).toFixed(1),
    violationCount: violations,
    violationPercentage: ((violations / total) * 100).toFixed(1)
  }
}

// 渲染所有图表
const renderCharts = () => {
  renderClassPieChart()
  renderDegreeBarChart()
  renderGenderPieChart()
  renderViolationBarChart()
  renderGradLineChart()
}

// 班级分布饼图
const renderClassPieChart = () => {
  // 按班级统计学生数量
  const classMap = {}
  students.value.forEach(student => {
    const className = getClassName(student.clazzId)
    if (!classMap[className]) {
      classMap[className] = 0
    }
    classMap[className]++
  })

  const chart = echarts.init(classPieChart.value)
  const option = {
    title: {
      text: '班级学生占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: Object.keys(classMap)
    },
    series: [
      {
        name: '学生数量',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.keys(classMap).map(className => ({
          value: classMap[className],
          name: className
        }))
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 学历分布柱状图
const renderDegreeBarChart = () => {
  // 学历映射
  const degreeMap = {
    1: '专科',
    2: '本科',
    3: '硕士',
    4: '博士',
    5: '其他'
  }
  
  // 按学历统计学生数量
  const degreeCount = {}
  students.value.forEach(student => {
    const degreeName = degreeMap[student.degree] || '其他'
    if (!degreeCount[degreeName]) {
      degreeCount[degreeName] = 0
    }
    degreeCount[degreeName]++
  })

  const chart = echarts.init(degreeBarChart.value)
  const option = {
    title: {
      text: '学历分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Object.keys(degreeCount),
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        data: Object.values(degreeCount),
        itemStyle: {
          color: function(params) {
            const colorList = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE']
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 性别分布饼图
const renderGenderPieChart = () => {
  const maleCount = students.value.filter(s => s.gender === 1).length
  const femaleCount = students.value.filter(s => s.gender === 2).length

  const chart = echarts.init(genderPieChart.value)
  const option = {
    title: {
      text: '性别分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['男', '女']
    },
    series: [
      {
        name: '性别分布',
        type: 'pie',
        radius: '70%',
        center: ['50%', '60%'],
        data: [
          { value: maleCount, name: '男', itemStyle: { color: '#5470C6' } },
          { value: femaleCount, name: '女', itemStyle: { color: '#EE6666' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 违纪情况柱状图
const renderViolationBarChart = () => {
  // 违纪分数区间
  const violationRanges = [
    { range: '无违纪', min: -Infinity, max: 0.5 },
    { range: '1-5分', min: 0.5, max: 5.5 },
    { range: '6-10分', min: 5.5, max: 10.5 },
    { range: '10分以上', min: 10.5, max: Infinity }
  ]
  
  const violationData = violationRanges.map(range => {
    const count = students.value.filter(s => 
      s.violationScore >= range.min && s.violationScore < range.max
    ).length
    return { range: range.range, count }
  })

  const chart = echarts.init(violationBarChart.value)
  const option = {
    title: {
      text: '违纪情况分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: violationData.map(item => item.range),
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        barWidth: '60%',
        data: violationData.map(item => item.count),
        itemStyle: {
          color: function(params) {
            const colorList = ['#91CC75', '#FAC858', '#EE6666', '#5470C6']
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 毕业年份分布折线图
const renderGradLineChart = () => {
  // 根据选择的时间范围生成不同的数据
  let xAxisData = []
  let seriesData = []
  
  if (gradRange.value === 'year') {
    // 按年统计
    const yearMap = {}
    students.value.forEach(student => {
      const year = new Date(student.graduationDate).getFullYear() + '年'
      if (!yearMap[year]) {
        yearMap[year] = 0
      }
      yearMap[year]++
    })
    
    xAxisData = Object.keys(yearMap).sort()
    seriesData = xAxisData.map(year => yearMap[year])
  } else {
    // 按月统计
    const monthMap = {}
    students.value.forEach(student => {
      const date = new Date(student.graduationDate)
      const month = `${date.getFullYear()}年${date.getMonth() + 1}月`
      if (!monthMap[month]) {
        monthMap[month] = 0
      }
      monthMap[month]++
    })
    
    // 按时间排序
    const sortedMonths = Object.keys(monthMap).sort((a, b) => {
      return new Date(a.replace('年', '-').replace('月', '')) - 
             new Date(b.replace('年', '-').replace('月', ''))
    })
    
    // 最多显示12个月
    xAxisData = sortedMonths.slice(-12)
    seriesData = xAxisData.map(month => monthMap[month])
  }

  const chart = echarts.init(gradLineChart.value)
  const option = {
    title: {
      text: '毕业年份分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLabel: {
        rotate: gradRange.value === 'month' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '毕业人数',
        type: 'line',
        stack: 'Total',
        data: seriesData,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(58, 77, 233, 0.8)'
            },
            {
              offset: 1,
              color: 'rgba(58, 77, 233, 0.1)'
            }
          ])
        },
        itemStyle: {
          color: '#3a4de9'
        },
        smooth: true
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 班级ID到名称的映射
const getClassName = (clazzId) => {
  const classMap = {
    1: '一班',
    2: '二班',
    4: '四班',
    8: '八班',
    3: '三班',
    5: '五班',
    6: '六班',
    7: '七班',
    9: '九班',
    10: '十班',
    11: '十一班',
    12: '十二班',
    13: '十三班',
    14: '十四班',
    15: '十五班',
    16: '十六班',
    17: '十七班',
    18: '十八班',

    // 根据实际情况添加更多班级映射
  }
  return classMap[clazzId] || `班级${clazzId}`
}

const handleGradRangeChange = () => {
  renderGradLineChart()
}

onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.student-statistics {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-card {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-compare {
  color: #909399;
  margin-left: 5px;
}

.mt-20 {
  margin-top: 20px;
}
</style>